//
//  ViewController.m
//  地图
//
//  Created by dllo on 16/5/24.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ViewController.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>


@interface ViewController ()<BMKMapViewDelegate,BMKGeoCodeSearchDelegate,BMKLocationServiceDelegate,BMKGeneralDelegate,BMKRouteSearchDelegate>
@property (nonatomic, strong) BMKMapView *mapView;
@property (nonatomic, strong) UIImageView *bomeImage;
@property (nonatomic, strong) UITextField *startCity;
@property (nonatomic, strong) UITextField *startAddress;
@property (nonatomic, strong) UITextField *endCity;
@property (nonatomic, strong) UITextField *endAddress;
@property (nonatomic, strong) BMKLocationService *locationServer;
@property (nonatomic, strong) BMKGeoCodeSearch *getCodeSearch;
@property (nonatomic, strong) BMKRouteSearch *routSearch;
@property (nonatomic, strong) BMKPlanNode *starNode;
@property (nonatomic, strong) BMKPlanNode *endNode;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
    BMKMapManager *manager = [[BMKMapManager alloc] init];
    BOOL result = [manager start:@"bZFMQuvH3UeahDoFwy9sCsalV1D1ICpd" generalDelegate:(id)self];// 启动引擎必须有的??
    if (!result) {
        NSLog(@"秘钥有问题");
        
    }
}
- (void)creatView
{
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"开始定位" style:UIBarButtonItemStylePlain target:self action:@selector(leftAction:)];
    self.navigationItem.leftBarButtonItem = left;
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"关闭定位" style:UIBarButtonItemStylePlain target:self action:@selector(rightAction:)];
    self.navigationItem.rightBarButtonItem = right;
    self.startCity = [[UITextField alloc] initWithFrame:CGRectMake(20, 80, 100, 30)];
    self.startCity.placeholder = @"开始城市";
    [self.view addSubview:self.startCity];
    self.startAddress = [[UITextField alloc] initWithFrame:CGRectMake(150, 80, 100, 30)];
    self.startAddress.placeholder = @"开始地址";
    [self.view addSubview:self.startAddress];
    
    self.endCity = [[UITextField alloc] initWithFrame:CGRectMake(20, 120, 100, 30)];
    self.endCity.placeholder = @"目的城市";
    [self.view addSubview:self.endCity];
    
    self.endAddress = [[UITextField alloc] initWithFrame:CGRectMake(150, 120, 100, 30)];
    self.endAddress.placeholder = @"目的地址";
    [self.view addSubview:self.endAddress];
    
    UIButton *routSearch = [UIButton buttonWithType:UIButtonTypeCustom];
    [routSearch setTitle:@"路线规划" forState:UIControlStateNormal];
    routSearch.frame = CGRectMake(300, 90, 100, 30);
    [routSearch setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [routSearch addTarget:self action:@selector(routSearch:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:routSearch];
    
    self.mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 150, self.view.frame.size.width, self.view.frame.size.height - 150)];
    self.mapView.delegate = self;
    [self.view addSubview:self.mapView];
}

- (void)leftAction:(UIButton *)button
{// 开启定位服务操作
    [self.locationServer startUserLocationService];
// 在地图上显示用户的位置
    self.mapView.showsUserLocation = YES;
}
- (void)rightAction:(UIButton *)button
{
    // 关闭定位服务
    [self.locationServer stopUserLocationService];
    // 设置地图不显示用户的位置
    self.mapView.showsUserLocation = NO;
    // 删除我们添加的标注对象
    [self.mapView removeAnnotation:[self.mapView.annotations firstObject]];
    NSLog(@"关闭定位");
}
- (void)routSearch:(UIButton *)button
{
    // 完成正向地理编码
    // 创建地理编码选项对象
    BMKGeoCodeSearchOption *geoSearchOption = [[BMKGeoCodeSearchOption alloc] init];
    // 给想进行正向地理位置编码的位置赋值
    geoSearchOption.city = self.startCity.text;
    geoSearchOption.address = self.startAddress.text;
    // 执行地理位置编码
    [self.getCodeSearch geoCode:geoSearchOption];
}

- (void)willStartLocatingUser
{
    NSLog(@"开始定位");
}
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"定位失败");
}
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    // 地理反编码
    // 创建反向地理编码选项对象
    BMKReverseGeoCodeOption *reverseOption = [[BMKReverseGeoCodeOption alloc] init];
    // 给反向地理编码选项的坐标点赋值
    reverseOption.reverseGeoPoint = userLocation.location.coordinate;// 当时的位置坐标
    // 执行反向地理编码操作
    [self.getCodeSearch reverseGeoCode:reverseOption];
}
// 反向的地理位置编码回调方法
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    // 插入大头针
    // 定义大头针标注
    BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init];
    // 设置标注的位置坐标
    annotation.coordinate = result.location;
    // 大头针显示的地址
    annotation.title = result.address;
    // 添加到地图
    [self.mapView addAnnotation:annotation];
    // 使地图显示该位置
    [self.mapView setCenterCoordinate:result.location animated:YES];
}
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if ([result.address isEqualToString:self.startAddress.text]) {
        // 说明当前编码的对象是开始点
        self.starNode = [[BMKPlanNode alloc] init];
        // 给节点坐标的位置赋值
        self.starNode.pt = result.location;
        // 发起对目标节点的地理编码
        BMKGeoCodeSearchOption *geoOption = [[BMKGeoCodeSearchOption alloc] init];
        geoOption.city = self.endCity.text;
        geoOption.address = self.endAddress.text;
        // 执行正向编码
        [self.getCodeSearch geoCode:geoOption];
        self.endNode = nil;
    }else{
        self.endNode = [[BMKPlanNode alloc] init];
        self.endNode.pt = result.location;
        if (self.starNode != nil && self.endNode != nil) {
            // 开始路线规划
            // 创建自驾路线规划
            BMKDrivingRoutePlanOption *drivingRoute = [[BMKDrivingRoutePlanOption alloc] init];
            drivingRoute.from = self.starNode;
            drivingRoute.to = self.endNode;
            //
            [self.routSearch drivingSearch:drivingRoute];
            
        }
    }
}

- (void)onGetDrivingRouteResult:(BMKRouteSearch *)searcher result:(BMKDrivingRouteResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSArray *array = [NSArray arrayWithArray:self.mapView.annotations];
    [self.mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:self.mapView.overlays];
    [self.mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        BMKDrivingRouteLine *plan = [result.routes objectAtIndex:0];
        NSUInteger size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKDrivingStep *step = plan.steps[i];
            if (i == 0) {
                CLLocationCoordinate2D mapCoordinate = step.entrace.location;
                self.mapView.centerCoordinate = mapCoordinate;
            }
            planPointCounts += step.pointsCount;
        }
        BMKMapPoint *tempPoints = [];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKDrivingStep *transStep = [plan.steps objectAtIndex:j];
            int k = 0;
            for (k = 0; k < transStep.pointsCount; k++) {
                tempPoints[i].x = transStep.points[k].x;
                tempPoints[i].y = transStep.points[k].y;
                i++;
            }
        }
        BMKPolyline *polyLine = [BMKPolyline polylineWithPoints:tempPoints count:planPointCounts];
        [self.mapView addOverlay:polyLine];
    }
}

- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id<BMKOverlay>)overlay
{
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView *polyLineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polyLineView.fillColor = [UIColor redColor];
        polyLineView.strokeColor = [UIColor redColor];
        polyLineView.lineWidth = 2.0;
        return polyLineView;
    }
    return nil;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
